<?php
namespace app\weixin\controller;

use cmf\controller\HomeBaseController;
use app\weixin\logic\WeixinLogic;

class IndexController extends HomeBaseController
{
    public function getToken()
    {
        $weixin=new WeixinLogic();
        $token=$weixin->getToken();
        if($token===false){
            $this->error($weixin->getError());
        }
        return $token;
    }
    public function getCallbackIP()
    {
        $weixin=new WeixinLogic();
        $url=$weixin->host."getcallbackip?access_token=".$weixin->getToken();
        $response=$weixin->get($url);
        var_dump($response);
    }
    /**
     * 获取用户信息(包括UnionID)
     */
    public function getUserInfo()
    {
        $weixin=new WeixinLogic();
        $url=$weixin->host."user/info?access_token=".$weixin->getToken()."&openid=OPENID&lang=zh_CN";
        $response=$weixin->get($url);
        var_dump($response);
    }
    public function receiveMessage()
    {
        $weixin=new WeixinLogic();
        $data = file_get_contents("php://input");
        if(!$data){
            print("ERR: null\n\n");
            exit;
        }
        $xml = new \DOMDocument();
        $xml->loadXML($data);
        $openID=$xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;
        $message=$xml->getElementsByTagName('Content')->item(0)->nodeValue;

        //处理消息
        $message="[自动回复]".$message;

        $timestamp=time();
        $data = '<xml>
            <ToUserName><![CDATA['.$openID.']]></ToUserName>
            <FromUserName><![CDATA['.$weixin->appid.']]></FromUserName>
            <CreateTime>'.$timestamp.'</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA['.$message.']]></Content>
        </xml>';
        echo $data;
        exit;
    }
}